<template>
  <div class="app-container">
    <!-- 搜索表单 -->
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="110px">
      <el-form-item label="生产工单编码" prop="workorderCode">
        <el-input v-model="queryParams.workorderCode" placeholder="请输入生产工单编码" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="产品名称" prop="itemName">
        <el-input v-model="queryParams.itemName" placeholder="请输入产品名称" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="老化临时编号" prop="agingCode">
        <el-input v-model="queryParams.agingCode" placeholder="请输入老化临时编号" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 状态图例 -->
    <div class="legend">
      <span class="legend-item charging">充电</span>
      <span class="legend-item discharging">放电</span>
      <span class="legend-item idle">搁置</span>
      <span class="legend-item pause">暂停</span>
      <span class="legend-item ending">结束</span>
      <span class="legend-item complete">完成</span>
      <span class="legend-item offline">离线</span>
      <span class="legend-item warning">保护</span>
    </div>

    <div class="content">
      <!-- 左侧设备选择列表 -->
      <div class="left-device-list">
        <div
          v-for="device in deviceList"
          :key="device"
          :class="['device-item', selectedDevice === device ? 'active-device' : '']"
          @click="selectDevice(device)"
        >
          {{ device === 'all' ? '全部' : '#' + device }}
        </div>
      </div>

      <!-- 网格列表 -->
      <div class="grid-container">
        <div
          v-for="(cell, index) in pagedCells"
          :key="index"
          class="cell-box"
          :class="processColorClass(cell.processName)"
          @click="handleCellClick(cell)"
        >
          <div class="cell-header">
            {{ cell.machineChannel }}
          </div>
          <div class="cell-content">
            <div class="process-name">{{ cell.processName }}</div>
            <div>{{ cell.ccEndVolume }}Ah</div>
            <div>{{ cell.dcEndVolume }}Ah</div>
            <div>{{ cell.processTime }}</div>
            <div>{{ cell.itemName }}</div>
          </div>
        </div>
      </div>
    </div>

    <!-- 分页控件 -->
    <pagination
      v-show="filteredCells.length > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 弹窗显示缩略图与嵌套展示三层数据 -->
    <el-dialog :visible.sync="popupVisible" title="详情" width="80%">
      <div class="popup-content">
        <div class="left-thumbnail">
          <img :src="cellThumbnail" alt="缩略图" style="width:100%; border:1px solid #ccc" />
        </div>
        <div class="right-details">
          <!-- 一级表格（循环基本信息） +  二级表格（工步基本信息） + 三级表格详细信息table -->
              <!-- 循环基本信息表格 -->
              <el-table :data="popupDetails">
                <!-- 工步基本信息表格 -->
                <el-table-column type="expand">
                  <template #default="props">
                    <div style="padding-left: 50px;">
                        <el-table  :data="props.row.batteryProcessInspectStatsList">
                            <!-- 详细表格 -->
                            <el-table-column type="expand">
                              <template #default="subProps">
                                <div style="padding-left: 50px;">
                                  <el-table :data="performanceDetails[subProps.row.id] || []">
                                    <el-table-column label="记录序号" prop="rowNum" />
                                    <el-table-column label="记录时间" prop="recordTime" />
                                    <el-table-column label="电压(V)" prop="voltage" />
                                    <el-table-column label="电流(A)" prop="electricity" />
                                    <el-table-column label="温度(℃)" prop="tempe" />
                                    <el-table-column label="容量(Ah)" prop="volume" />
                                    <el-table-column label="绝对时间" prop="absoluteTime" />
                                    <el-table-column label="功率(W)" prop="power" />
                                    <el-table-column label="工步时间" prop="processTime" />
                                    <el-table-column label="能量(Wh)" prop="energy" />
                                  </el-table>
                                </div>
                              </template>
                            </el-table-column>
                          <el-table-column  label="工步类型" prop="processName"></el-table-column >
                          <el-table-column  label="工步时间" prop="processTime"></el-table-column >
                          <el-table-column  label="终止容量" prop="endVoltage"></el-table-column >
                          <el-table-column  label="起始电压" prop="startVoltage"></el-table-column >
                          <el-table-column  label="终止电压" prop="endVoltage"></el-table-column >
                          <el-table-column  label="起始温度" prop="startTempe"></el-table-column >
                          <el-table-column  label="终止温度" prop="endTempe"></el-table-column >
                          <el-table-column  label="充电中值电压" prop="chargeMiddleVoltage"></el-table-column >
                          <el-table-column  label="放电中值电压" prop="dischargeMiddleVoltage"></el-table-column >
                          <el-table-column  label="原工步号" prop="origProcessSeq"></el-table-column >
                          <el-table-column  label="能量" prop="energy"></el-table-column >
                          <!-- <el-descriptions-item label="截止最大单体电压">{{ item.startVoltage }}</el-descriptions-item>
                          <el-descriptions-item label="截止最小单体电压">{{ item.startVoltage }}</el-descriptions-item>
                        <el-descriptions-item label="截止单体压差">{{ item.startVoltage }}</el-descriptions-item> -->
                      </el-table >
                    </div>
                  </template>
                  </el-table-column>
                   
                <el-table-column  label="充电容量" prop="chargeVolume"></el-table-column >
                <el-table-column  label="放电容量" prop="dischargeVolume"></el-table-column >
                <el-table-column  label="充电时间" prop="chargeTime"></el-table-column >
                <el-table-column  label="放电时间" prop="dischargeTime"></el-table-column >
                <el-table-column  label="中值电压" prop="middleVoltage"></el-table-column >
                <el-table-column  label="充电能量" prop="chargeEnergy"></el-table-column >
                <el-table-column  label="放电能量" prop="dischargeEnergy"></el-table-column >
                <el-table-column  label="横流充入比例" prop="hlChargeRatio"></el-table-column >
                <el-table-column  label="横流充入容量" prop="hlChargeVolume"></el-table-column >
                <el-table-column  label="充电开始电压" prop="startChargeVoltage"></el-table-column >
                <el-table-column  label="充电结束电压" prop="endChargeVoltage"></el-table-column >
                <el-table-column  label="放电开始电压" prop="startDischargeVoltage"></el-table-column >
                <el-table-column  label="放电结束电压" prop="endDischargeVoltage"></el-table-column >
                <el-table-column  label="放电容量衰减比" prop="dischargeVolumeRatio"></el-table-column >
                <el-table-column  label="充放电效率" prop="efficiency"></el-table-column >
              </el-table>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getBatteryPerformanceList, getBatteryPerformanceChannel, getBatteryPerformanceDetail } from "@/api/mes/pro/batteryPerformance";
export default {
  name: "BatteryPerformance",
  data() {
    return {
      showSearch: true,
      queryParams: {
        pageNum: 1,
        pageSize: 30,
        workorderCode: null,
        itemName: null,
        agingCode: null,
      },
      cellList: [],
      popupVisible: false,
      cellThumbnail: '',
      popupDetails: [],
      selectedDevice: 'all',
      performanceDetails: {}, // 存储第三级表格数据，以工步ID为键
      total: 0,

    };
  },
  computed: {
    deviceList() {
      // 按照序号排序
      const deviceSet = new Set(this.cellList.map(c => c.machine));
      return ['all', ...Array.from(deviceSet).sort((a, b) => a - b)];
    },
    filteredCells() {
      if (this.selectedDevice === 'all') return this.cellList;
      return this.cellList.filter(c => c.machine === this.selectedDevice);
    },
    pagedCells() {
      const start = (this.queryParams.pageNum - 1) * this.queryParams.pageSize;
      return this.filteredCells.slice(start, start + this.queryParams.pageSize);
    }
  },
  mounted() {
    this.getList();
  },
  methods: {
    selectDevice(device) {
      this.selectedDevice = device;
      this.queryParams.pageNum = 1;
      this.getList();
    },
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    resetQuery() {
      this.$refs.queryForm.resetFields();
      this.handleQuery();
    },
    handleCellClick(cell) {
      getBatteryPerformanceChannel(cell.id).then(res => {
        if(res.data.length > 0) {
          this.cellThumbnail = res.data[0].picture;
          this.popupDetails = res.data;
          
          // 清空之前的性能详情数据
          this.performanceDetails = {};
          
          // 获取每个工步的详细信息
          const processPromises = [];
          res.data.forEach(item => {
            if (item.batteryProcessInspectStatsList && item.batteryProcessInspectStatsList.length > 0) {
              item.batteryProcessInspectStatsList.forEach(process => {
                if (process.id) {
                  processPromises.push(
                    getBatteryPerformanceDetail(process.id).then(detailRes => {
                      if (detailRes.data) {
                        this.$set(this.performanceDetails, process.id, detailRes.data);
                      }
                    })
                  );
                }
              });
            }
          });
          
          // 等待所有工步详情数据加载完成
          Promise.all(processPromises).then(() => {
            console.log('所有工步详情数据加载完成', this.performanceDetails);
          });
        }
      })
      this.popupVisible = true;
    },
    getList() {
      getBatteryPerformanceList(this.queryParams).then(res => {
        this.cellList = res.rows || [];
        this.total = res.total;

      });
    },
    processColorClass(name) {
      const map = {
        '充电': 'charging',
        '放电': 'discharging',
        '静置': 'idle',
        '暂停': 'pause',
        '结束': 'ending',
        '完成': 'complete',
        '离线': 'offline',
        '保护': 'warning'
      };
      return map[name] || '';
    }
  },
};
</script>

<style scoped>
.content {
  display: flex;
}
.left-device-list {
  width: 100px;
  display: flex;
  flex-direction: column;
  padding: 5px 0;
}
.device-item {
  width: 70px;
  color: #fff;
  text-align: center;
  padding: 8px 4px;
  margin: 2px 0;
  transition: all 0.2s ease;
  cursor: pointer;
  background-color: #177245;
}
.device-item:hover,
.active-device {
  padding-left: 12px;
  padding-right: 12px;
  background-color: #1b8c55;
  font-weight: bold;
  transform: scaleX(1.1);
  transform-origin: left center;
}

.grid-container {
  display: grid;
  grid-template-columns: repeat(10, 1fr);
  gap: 10px;
  margin-left: 10px;
  flex: 1;
}
.cell-box {
  padding: 10px;
  background-color: #eee;
  border: 1px solid #ccc;
  cursor: pointer;
  text-align: center;
  display: flex;
  flex-direction: column;
  min-height: 120px;
  height: 250px;
}
.cell-header{
  font-weight: bold;
  margin-bottom: 30px;
  margin-top: 20px;
}
.cell-content div {
  text-align: center;
  margin-bottom: 8px;
}
.process-name {
  font-weight: bold;
}
.cell-box.charging { background-color: #ffb6b6; }
.cell-box.discharging { background-color: #fd934d; }
.cell-box.idle { background-color: #72db7b; }
.cell-box.pause { background-color: #8080ff; }
.cell-box.ending { background-color: #9990c1; }
.cell-box.complete { background-color: #16798c; color: white; }
.cell-box.offline { background-color: #cccccc; }
.cell-box.warning { background-color: #ff4c4c; color: white; }

.popup-content {
  display: flex;
  gap: 20px;
}
.left-thumbnail {
  width: 30%;
}
.right-details {
  width: 70%;

}

.legend {
  display: flex;
  gap: 10px;
  margin: 10px 0;
  flex-wrap: wrap;
}
.legend-item {
  padding: 5px 10px;
  border-radius: 4px;
  font-size: 14px;
  color: white;
}
.legend-item.charging { background-color: #ffb6b6; }
.legend-item.discharging { background-color: #fd934d; }
.legend-item.idle { background-color: #72db7b; }
.legend-item.pause { background-color: #8080ff; }
.legend-item.ending { background-color: #9990c1; }
.legend-item.complete { background-color: #16798c; }
.legend-item.offline { background-color: #cccccc; color: black; }
.legend-item.warning { background-color: #ff4c4c; }

.pagination {
  margin-top: 20px;
  text-align: center;
}
</style>